package com.lkd.handler;

import com.lkd.business.MsgHandler;
import com.lkd.common.VMSystem;
import com.lkd.config.TopicConfig;
import com.lkd.contract.SupplyContract;
import com.lkd.emq.Topic;
import com.lkd.feign.VMService;
import com.lkd.http.vo.TaskDetailsViewModel;
import com.lkd.http.vo.TaskViewModel;
import com.lkd.service.TaskService;
import com.lkd.utils.JsonUtil;
import com.lkd.vo.VmVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.stream.Collectors;


@Component
@Slf4j
@Topic(TopicConfig.TASK_SUPPLY_TOPIC)
public class SupplyTaskHandler implements MsgHandler {

    @Autowired
    private VMService vmService;

    @Autowired
    private TaskService taskService;
    @Override
    public void process(String jsonMsg) throws IOException {
        try {
            var supplyContract = JsonUtil.getByJson(jsonMsg, SupplyContract.class);
            if (supplyContract==null){
                return;
            }
            var vm = vmService.getVMInfo(supplyContract.getInnerCode());
            var userId = taskService.getLeastUser(vm.getRegionId(), false);
            if(vm==null || userId==0){
                return;
            }
            var taskViewModel = new TaskViewModel();
            taskViewModel.setUserId(userId);
            taskViewModel.setCreateType(0);
            taskViewModel.setProductType(VMSystem.TASK_TYPE_SUPPLY);
            taskViewModel.setInnerCode(supplyContract.getInnerCode());
            taskViewModel.setAssignorId(0);
            taskViewModel.setDesc("自动补货工单");


            taskViewModel.setDetails(supplyContract.getSupplyData().stream().map(
                    c->{
                        var taskDetailsViewModel = new TaskDetailsViewModel();
                        taskDetailsViewModel.setChannelCode(c.getChannelId());
                        taskDetailsViewModel.setExpectCapacity(c.getCapacity());
                        taskDetailsViewModel.setSkuId(c.getSkuId());
                        taskDetailsViewModel.setSkuName(c.getSkuName());
                        return taskDetailsViewModel;
                    }).collect(Collectors.toList()
            ));

            taskService.createTesk(taskViewModel);
        } catch (IOException e) {
            e.printStackTrace();
            log.error("创建自动补货工单出错"+e.getMessage());
        }
    }
}
